package com.zj.inoutput.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @author DuanYu Email:<a>z-houjie@qq.com</a>
 * @date 2022-02-21 16:52
 */
@Slf4j
public class FileUtils extends FileUtil {

    private static final String TMP_PATH = File.separator + "tmp" + File.separator;

    /**
     * MultipartFile 转 File
     *
     * @param file MultipartFile
     * @throws IOException io异常
     */
    public static File multipartFileToFile(MultipartFile file) throws IOException {
        InputStream ins = file.getInputStream();
        File toFile = new File(TMP_PATH + URLEncoder.encode(Objects.requireNonNull(file.getOriginalFilename()), "UTF-8"));
        toFile.getParentFile().mkdirs();
        FileUtil.writeFromStream(ins, toFile);
        return toFile;
    }

    /**
     * base64转文件
     *
     * @param base64   base64
     * @param fileName 文件名称
     * @return 文件
     * @throws UnsupportedEncodingException 编码异常
     */
    public static File base64ToFile(String base64, String fileName) throws UnsupportedEncodingException {
        return Base64.decodeToFile(base64, new File(TMP_PATH + URLEncoder.encode(fileName, "UTF-8")));
    }

}
